// Secure preload script with explicit API exposure
const { contextBridge, ipcRenderer } = require('electron');

// Define allowed IPC channels for security
const ALLOWED_CHANNELS = {
    // Case management
    'get-cases': true,
    'get-case-by-id': true,
    'create-case': true,
    'update-case': true,
    'delete-case': true,
    'export-case': true,
    'import-case': true,

    // Data operations
    'import-data-to-database': true,
    'get-case-data': true,
    'export-data': true,
    'delete-case-data': true,
    'clear-case-data': true,
    'clear-all-data': true,
    'clear-import-log': true,
    'execute-query': true,

    // File operations
    'select-export-path': true,
    'select-import-file': true,
    'select-save-file': true,
    'read-text-file': true,
    'parse-file': true,
    'inspect-files': true,
    'select-directory': true,

    // Navigation
    'open-workbench': true,
    'go-to-main-page': true,

    // Config
    'config:save-profile': true,
    'config:get-profiles': true,
    'config:get-storage-path': true,
    'config:set-storage-path': true,
    'config:get-log-path': true,
    'config:set-log-path': true,
    'config:get-log-content': true,

    // AI
    'ai:save-template': true,
    'ai:get-template': true,
    'ai:get-config': true,
    'ai:save-config': true,

    // Schema
    'schema:get-all': true,
    'schema:get-by-name': true,
    'schema:sync': true,
    'schema:sync-case': true,
    'schema:create': true,
    'schema:update': true,
    'schema:delete': true,

    // Profile
    'profile.create': true,
    'profile.get': true,
    'profile.search': true,
    'profile.list': true,
    'profile.findByIdCard': true,
    'profile.extractFromBank': true,
    'profile:build': true,
    'profile:get-entities': true,
    'profile:get-graph': true,
    'profile:get-timeline': true,

    // Analysis
    'analysis:funds-trace': true,
    'analysis:save-report': true,
    'analysis:load-report': true,
    'analysis:delete-report': true,
    'analysis:list-plugins': true,
    'analysis:run-plugin': true,
    'analysis:import-plugin': true,

    // Search
    'search:global': true
};

/**
 * Secure IPC invoke wrapper with channel validation
 */
function secureInvoke(channel, ...args) {
    if (!ALLOWED_CHANNELS[channel]) {
        throw new Error(`IPC channel '${channel}' is not allowed`);
    }
    return ipcRenderer.invoke(channel, ...args);
}

contextBridge.exposeInMainWorld('electronAPI', {
    // Case management API
    case: {
        getAll: (filter) => secureInvoke('get-cases', filter),
        getById: (id) => secureInvoke('get-case-by-id', id),
        create: (caseData) => secureInvoke('create-case', caseData),
        update: (updateData) => secureInvoke('update-case', updateData),
        delete: (caseId) => secureInvoke('delete-case', caseId),
        export: (caseId, formData) => secureInvoke('export-case', caseId, formData),
        import: (filePath, formData) => secureInvoke('import-case', filePath, formData),
    },

    // Data operations API
    data: {
        import: (importData) => secureInvoke('import-data-to-database', importData),
        get: (params) => secureInvoke('get-case-data', params),
        export: (options) => secureInvoke('export-data', options),
        delete: (options) => secureInvoke('delete-case-data', options),
        clear: (params) => secureInvoke('clear-all-data', params),
        clearAll: (params) => secureInvoke('clear-all-data', params),
        clearImportLog: (params) => secureInvoke('clear-import-log', params),
        query: (params) => secureInvoke('execute-query', params),
    },

    // File selection API
    file: {
        selectExportPath: () => secureInvoke('select-export-path'),
        selectImportFile: (options) => secureInvoke('select-import-file', options),
        selectSaveFile: (options) => secureInvoke('select-save-file', options),
        selectDirectory: (options) => secureInvoke('select-directory', options),
        readText: (filePath) => secureInvoke('read-text-file', filePath),
        parse: (filePath, dataType, options) => secureInvoke('parse-file', { filePath, dataType, options }),
        inspectFiles: (filePaths) => secureInvoke('inspect-files', filePaths)
    },

    // Page navigation API
    navigation: {
        openWorkbench: (options) => ipcRenderer.send('open-workbench', options),
        goToMainPage: () => secureInvoke('go-to-main-page'),
        onActivateTab: (callback) => {
            const subscription = (_event, data) => callback(data);
            ipcRenderer.on('activate-tab', subscription);
            return () => ipcRenderer.removeListener('activate-tab', subscription);
        },
        removeActivateTabListener: (callback) => {
            ipcRenderer.removeListener('activate-tab', callback);
        },
    },

    // Configuration API
    config: {
        saveProfile: (profile) => secureInvoke('config:save-profile', profile),
        getProfiles: () => secureInvoke('config:get-profiles'),
        getStoragePath: () => secureInvoke('config:get-storage-path'),
        setStoragePath: (path) => secureInvoke('config:set-storage-path', path),
        getLogPath: () => secureInvoke('config:get-log-path'),
        setLogPath: (path) => secureInvoke('config:set-log-path', path),
        getLogContent: () => secureInvoke('config:get-log-content'),
    },

    // AI API
    ai: {
        saveTemplate: (data) => secureInvoke('ai:save-template', data),
        getTemplate: (sceneKey) => secureInvoke('ai:get-template', sceneKey),
        getConfig: () => secureInvoke('ai:get-config'),
        saveConfig: (config) => secureInvoke('ai:save-config', config),
        chat: (messages, onToken, onEnd, onError) => {
            ipcRenderer.send('ai:chat-start', messages);

            const tokenListener = (_event, token) => onToken(token);
            const endListener = () => onEnd();
            const errorListener = (_event, err) => onError(err);

            ipcRenderer.on('ai:stream', tokenListener);
            ipcRenderer.on('ai:stream-end', endListener);
            ipcRenderer.on('ai:error', errorListener);

            return () => {
                ipcRenderer.removeListener('ai:stream', tokenListener);
                ipcRenderer.removeListener('ai:stream-end', endListener);
                ipcRenderer.removeListener('ai:error', errorListener);
            };
        }
    },

    // Schema API
    schema: {
        getAll: () => secureInvoke('schema:get-all'),
        getByName: (name) => secureInvoke('schema:get-by-name', name),
        sync: () => secureInvoke('schema:sync'),
        syncCase: (caseId, dbPath) => secureInvoke('schema:sync-case', caseId, dbPath),
        create: (schemaDef) => secureInvoke('schema:create', schemaDef),
        update: (name, changes) => secureInvoke('schema:update', name, changes),
        delete: (name, dropTable) => secureInvoke('schema:delete', name, dropTable),
    },

    // Profile API (人物档案)
    profile: {
        create: (caseId, data) => secureInvoke('profile.create', { caseId, data }),
        get: (caseId, profileId) => secureInvoke('profile.get', { caseId, profileId }),
        search: (caseId, query, options) => secureInvoke('profile.search', { caseId, query, options }),
        list: (caseId, page, pageSize, entityType) => secureInvoke('profile.list', { caseId, page, pageSize, entityType }),
        findByIdCard: (caseId, idCard) => secureInvoke('profile.findByIdCard', { caseId, idCard }),
        extractFromBank: (caseId, tableName) => secureInvoke('profile.extractFromBank', { caseId, tableName }),
        build: (caseId) => secureInvoke('profile:build', caseId),
        getEntities: (caseId) => secureInvoke('profile:get-entities', caseId),
        getGraph: (caseId) => secureInvoke('profile:get-graph', caseId),
        getTimeline: (params) => secureInvoke('profile:get-timeline', params),
    },

    // Analysis API
    analysis: {
        traceFunds: (params) => secureInvoke('analysis:funds-trace', params),
        saveReport: (caseId, subjectId, reportData) => secureInvoke('analysis:save-report', { caseId, subjectId, reportData }),
        loadReport: (caseId, subjectId) => secureInvoke('analysis:load-report', { caseId, subjectId }),
        deleteReport: (caseId, subjectId) => secureInvoke('analysis:delete-report', { caseId, subjectId }),
        listPlugins: () => secureInvoke('analysis:list-plugins'),
        runPlugin: (pluginId, caseId, params) => secureInvoke('analysis:run-plugin', { pluginId, caseId, params }),
        importPlugin: (path) => secureInvoke('analysis:import-plugin', path),
    },

    // Global Search API
    search: {
        global: (caseId, query, options) => secureInvoke('search:global', { caseId, query, options })
    }
});